package com.lepu.app.fun.tool.bmi;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.eyzhs.app.R;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class BmiActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,AsyncRequest {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_bmi_activity);

		UtilityBase.setStatusBarRes(this, R.color.color_bmi, true);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("BMI");
		topbar.setTopbarBackground(R.color.color_bmi);
		topbar.setonTopbarNewLeftLayoutListener(this);

		EditText weightEditText = (EditText) findViewById(R.id.weightEditText);
		weightEditText.addTextChangedListener(new CustomTextWatcher(
				weightEditText));
		
		EditText heightEditText = (EditText) findViewById(R.id.heightEditText);
		heightEditText.addTextChangedListener(new CustomTextWatcher(
				heightEditText));
	}

	class CustomTextWatcher implements TextWatcher {

		EditText contentEditText;

		public CustomTextWatcher(EditText editText) {
			contentEditText = editText;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			String content = s.toString().trim();

			if (TextUtils.isEmpty(content)) {

			} else {
				// new
				if (content.contains(".")) {
					if (s.length() - 1 - content.indexOf(".") > 2) {
						s = content.subSequence(0,
								content.indexOf(".") + 3);
						contentEditText.setText(s);
						contentEditText.setSelection(s.length());
					}
				}
				
				if (content.substring(0).equals(".")) {
					s = "0" + s;
					contentEditText.setText(s);
					contentEditText.setSelection(2);
				}

				if (content.startsWith("0")
						&& content.length() > 1) {
					if (!content.substring(1, 2).equals(".")) {
						contentEditText.setText(s.subSequence(0, 1));
						contentEditText.setSelection(1);
						return;
					}
				}
				
				//小数点前限制前3位
				int value = UtilityBase.parseInt(content);
				if(value >= 1000){
					content = content.substring(0,3);
					contentEditText.setText(content);
					contentEditText.setSelection(content.length());
				}
			}
		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	}
	
	public void request(double height,double weight,String result) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID",
					MyApplication.getInstance().getLoginInfo().UserID);
			params.put("LoginToken",
					MyApplication.getInstance().getLoginInfo().LoginToken);
			
			params.put("Height", height);
			params.put("Weight", weight);
			params.put("BMI", result);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getBmiUrl(), map, null, this,
				"", false);
	}

	@SuppressLint("DefaultLocale")
	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.testButton:

			EditText weightEditText = (EditText) findViewById(R.id.weightEditText);
			EditText heightEditText = (EditText) findViewById(R.id.heightEditText);

			String weight = weightEditText.getText().toString().trim();//kg
			String height = heightEditText.getText().toString().trim();//cm

			double weightValue = UtilityBase.parseDouble(weight);
			double heightValue = UtilityBase.parseDouble(height);

			if (TextUtils.isEmpty(weight)) {
				UIHelper.showToast(this, "请完整填写 体重");
				return;
			}

			if (weightValue == 0) {
				UIHelper.showToast(this, "请正确填写 体重");
				return;
			}
			
			if (TextUtils.isEmpty(height)) {
				UIHelper.showToast(this, "请完整填写 身高");
				return;
			}

			if (heightValue == 0) {
				UIHelper.showToast(this, "请正确填写 身高");
				return;
			}

			// BMI=体重（kg）÷ 身高^2（m）
			double resultValue = weightValue / Math.pow(heightValue/100.0, 2);

			String result = String.format("%.2f", resultValue);
			
			//submit net
			request(weightValue, heightValue, result);
			
			weightEditText.setText("");
			heightEditText.setText("");
			
			weightEditText.clearFocus();
			heightEditText.clearFocus();
			
			//jump result
			Intent intent = new Intent(this, BmiResultActivity.class);
			intent.putExtra("result", result);
			startActivity(intent, true);
			break;

		default:
			break;
		}
	}

	@Override
	public void RequestComplete(Object arg0, Object arg1) {
		LogUtilBase.LogD(null, "提交bmi success");
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		LogUtilBase.LogD(null, "提交bmi fail");
	}

}
